package com.soup.lab.third.token;

import com.soup.lab.third.lock.KeyLock;
import com.soup.lab.third.lock.RedisKeyLock;
import redis.clients.jedis.JedisCluster;

import java.util.Objects;
import java.util.function.Function;

/**
 * 便于生成 redisTokenFetcher，并让它们共享 {@link #jedisCluster} 和 {@link #keyLock} 实例。
 *
 * @see RedisTokenFetcher
 */
public class RedisTokenHelper {

    private JedisCluster jedisCluster;

    private KeyLock keyLock;

    public RedisTokenHelper(JedisCluster jedisCluster) {
        this.jedisCluster = Objects.requireNonNull(jedisCluster);
        this.keyLock = new RedisKeyLock(jedisCluster);
    }

    public TokenFetcher createRedisTokenFetcher(TokenFetcher tokenFetcher, Function<TokenConfig, String> redisKeyGetter) {
        return new RedisTokenFetcher(jedisCluster, keyLock, tokenFetcher, redisKeyGetter);
    }

    public TokenFetcher createRedisTokenFetcher(TokenFetcher tokenFetcher) {
        return new RedisTokenFetcher(jedisCluster, keyLock, tokenFetcher, tokenConfig -> tokenConfig.getGroup()+":"+tokenConfig.getTokenAuth().getKey());
    }

    public Token fetchToken(TokenFetcher tokenFetcher, TokenConfig config, boolean forceUpdate) {
        return new RedisTokenFetcher(jedisCluster, keyLock, tokenFetcher, tokenConfig -> tokenConfig.getGroup()+":"+tokenConfig.getTokenAuth().getKey())
                .fetchToken(config, forceUpdate);
    }

}
